package wh.ispct

import wh.ispct.util.ExtTreeData
import wh.ispct.util.ExtTreeNode
import wh.ispct.util.Msg
import java.text.MessageFormat

class MenuController {

	/**
	 * 显示每个类别进入后
	 * root ： 根菜单（如果当前菜单无子为其父）
	 * children：子菜单目录
	 * menu: 当前显示的菜单，若当前菜单有子，则默认为first子菜单
	 * 
	 * @return
	 */
	def show() {
		Menu root = null
		Menu m = Menu.get(params.id)
		List<Menu> children = Menu.findAllByParentMenu(m)
		//println 'children size of ' + m.name + " is "+ children.size()
		//叶子类别，目录从其父类别开始，子目录保护其自身
		if(children.size() == 0){
			root = m.parentMenu
			if(root)
				children = Menu.findAllByParentMenu(root)
		}else{
			root = m
			m = children[0]
		}

		//路径path
		Menu leaf = m
		List<Menu> path = new ArrayList<Menu>()
		while(leaf !=null) {
			path.add(0,leaf)
			leaf = leaf.parentMenu
		}
		println m.name + m.singleContent
		if(m.singleContent){
			//显示内容
			Content content = Content.findByMenu(m)
			println "singleContent:" + (content ? content.title : null)
			render (view:"show",model:["root":root,"children":children,"path":path,"menu":m,"singelContent":content])
		}else{
			//显示列表
			def max =  20
			def offset = 0
			if(params.max) max = params.max.toInteger()
			if(params.offset) offset = params.offset.toInteger()

			List<Content> contentList = Content.findAllByMenu(m,["max":max,"offset":offset,sort:"id",order:"desc"])

			def total = Content.countByMenu(m)

			//println "count m " + root

			render (view:"grid",
					model:["root":root,"menu":m,"children":children,"path":path,"contentList":contentList,
						"offset":offset,"max":max,"total":total])
		}
	}

	/**
	 * 列出所有内容字段
	 * @return
	 */
	def listContentMenus(){
		def msg = ["success":true]
		try{
			List<Menu> cotentMenus = Menu.findAll("from Menu as m where m.type=? and m.singleContent=?", ['content', false])
			msg.data = cotentMenus
		}catch(Exception e){
			e.printStackTrace()
			msg["success"] = false
			msg.error = e.message
		}

		render  (contentType:"text/json"){ msg }
	}

	def read(){
		def msg = ["success":true]
		try{
			Menu m = Menu.load(Integer.valueOf(params.id))
			if(m == null)
				throw new Exception("没找到菜单id=" + params.id)
			msg["menu"] =m
		}catch(Exception e){
			e.printStackTrace()
			msg["success"] = false
			msg.error = e.message
		}
		render  (contentType:"text/json"){ msg }
	}

	/**
	 * 保存菜单
	 * @return
	 */
	def save(){
		def msg = ["success":true]
		try{
			Menu m = params.id ? Menu.load(params.id) : new Menu()
			m.properties = params
			m.parentMenu = Menu.load(params.parentMenuId)

			if(!m.validate())
				m.errors.each {
					throw new Exception(MessageFormat.format(it.fieldError.getDefaultMessage(),it.fieldError.arguments))
				}

			m.save()
		}catch(e){
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}

	def delete(){
		def msg = ["success":true]
		try{
			Menu m = Menu.get(params.id)

			if(m==null)
				throw new Exception("菜单不存在")

			if("system".equals(m.type))
				throw new Exception("系统菜单，不能删除")

			if(Menu.findByParentMenu(m) !=null)
				throw new Exception("有子菜单，不能删除")

			if(Content.findByMenu(m)!=null)
				throw new Exception("有内容，不能删除")

			m.delete()
		}catch(e){
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}

	def drop(){
		def msg = ["success":true]
		try{
			Menu drop = Menu.load(params.dropId)
			Menu target = params.targetId? Menu.get(params.targetId) : null

			if("append".equals(params.point)){
				drop.parentMenu = target
			}else{ // above or below 不考虑上线移动排序问题
				drop.parentMenu = target == null ? null : target.parentMenu
			}
			drop.save()
		}catch(e){
			msg.put("success", false)
			msg.put("msg", e.getMessage())
		}
		render  (contentType:"text/json"){ msg }
	}

	def tree(){
		ExtTreeData<Menu> treeData = Menu.getTreeData()
		render  (contentType:"text/json"){ treeData.roots }
	}

	def createTestContet(){
		Menu m = Menu.get(params.id)

		for(def i=0;i < 55;i++){
			Content c = new Content()
			c.menu = m
			c.title = m.name + i
			c.text = m.name + "text"
			c.source = m.name+i
			c.author = m.name+i
			c.save()
		}
		render (text: "Ok")
	}

}
